#include "SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if(ps->size == ps->capacity)
	{
	int newcapacity = ps->capacity==0?4:2*ps->capacity;
	SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity*sizeof(SLDataType));
	assert(tmp);
	ps->a = tmp;
	tmp = NULL;
	ps->capacity = newcapacity;
	}
}

void SLPushBack(SL* ps,SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	ps->a[ps->size++] = x;
}

void SLPushFront(SL* ps,SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	for(size_t i = ps->size;i > 0;i--)
	{
		ps->a[i] = ps->a[i-1];
	}
	ps->a[0] = x;
	ps->size++;
}

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(!SLIsEmpty(ps));
	ps->size--;
}


void SLPopFront(SL* ps)
{
	assert(ps);
	assert(!SLIsEmpty(ps));
	for(size_t i = 0;i < ps->size-1;i++)
	{
		ps->a[i] = ps->a[i+1];
	}
	ps->size--;
}


bool SLIsEmpty(SL* ps)
{
	assert(ps);
	return ps->size==0;
}

void SLPrint(SL* ps)
{
	assert(ps);
	for(int i = 0;i<ps->size;i++)
	{
		printf("%d ",ps->a[i]);
	}
	printf("\n");
}

void SLInsert(SL* ps,size_t pos,SLDataType x)//在指定位置增加数据
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);//对pos的范围要进行限制
	SLCheckCapacity(ps);
	for(size_t i = ps->size;i > pos;i--)
	{
		ps->a[i] = ps->a[i-1];
	}
	ps->a[pos] = x;
	ps->size++;
}

void SLErase(SL* ps,size_t pos)
{
	assert(ps);
	assert(!SLIsEmpty(ps));
	assert(pos >= 0 && pos < ps->size);
	for(size_t i = pos; i < ps->size-1;i++)
	{
		ps->a[i] = ps->a[i+1];
	}
	ps->size--;
}
